import React, { useEffect, useState } from 'react'
import { Link, Routes, Route, useNavigate } from 'react-router-dom';
import GenalSonglist from '../songLists/genalSonglist';
import '../../style/kuangjia.css'
import '../../style/main.css'
import { useGlobalContext } from '../GlobalContext';
const favormusic = () => {
  const { userId, setUserId, favsongrefresh, setFavsongRefresh } = useGlobalContext();
  const [userfavorData, setUserfavorData] = useState([]);
  const getPlayUrl = (id) => {
    return fetch(`http://localhost:3000/song/url?id=${id}`)
      .then((response) => response.json())
      .then((data) => data.data[0]?.url || '')
      .catch((error) => {
        console.error('Error fetching song URL:', error);
        return '';
      });
  };
  useEffect(() => {
    const fetchUserFavorites = async () => {
      try {
        const response = await fetch(`http://localhost:8088/favor/userall/${userId}`);
        const data = await response.json();
        const favoritesWithUrls = await Promise.all(
          data.data.map(async (song) => ({
            ...song,
            playUrl: await getPlayUrl(song.musicId),
          }))
        );

        setUserfavorData(favoritesWithUrls);
      } catch (error) {
        console.error('Error fetching user favorites:', error);
      }
    };

    fetchUserFavorites();
  }, [userId, favsongrefresh]);
  return (
    <div className="favor">
      <div className="recent_top">
        <p className="titl">喜欢</p>
        <div className="recent_nav">
          <div className="recent_nav_li">
            <ul>
              <Link to="songs"><li className="click3">歌曲</li></Link>
              <li>歌单</li>
              <li>视频</li>
            </ul>
          </div>
        </div>
      </div>
      <div className="recent_main">
        <Routes>
          <Route path='songs' element={<GenalSonglist songData={userfavorData} />} />
        </Routes>
      </div>
    </div>
  )
}

export default favormusic